package genetic.evolution;

import genetic.GeneticProgram;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class Basic1 implements EvolutionaryStrategy {

	@Override
	public ArrayList<GeneticProgram> evolve(ArrayList<GeneticProgram> currentPopulation) {

		Collections.sort(currentPopulation);

		// neue Population aus alter erzeugen
		Random rd = new Random();
		ArrayList<GeneticProgram> newPopulation = new ArrayList<GeneticProgram>();

		// 4/5 der neuen Population erzeugen durch crossover mit dem
		// besten 1/5 der alten Population
		for (int i = 0; i < currentPopulation.size() * 4 / 5; i++) {

			int p1 = rd.nextInt(currentPopulation.size() / 5);
			int p2;
			do {
				p2 = rd.nextInt(currentPopulation.size() / 5);
			} while (p2 == p1);

			newPopulation.add(GeneticProgram.crossover(currentPopulation
					.get(p1), currentPopulation.get(p2)));
		}

		// 1/5-1 der neuen Population als Transfer der alten Population
		for (int i = 0; i < (currentPopulation.size() / 5) - 1; i++) {
			int num = rd.nextInt(currentPopulation.size());
			newPopulation.add((GeneticProgram) (currentPopulation.get(num))
					.clone());
		}

		// das beste der alten Population wird sowieso behalten
		newPopulation.add((GeneticProgram) (currentPopulation.get(0)).clone());
		
		return newPopulation;
	}

}
